package com.ling.sbbyyds.datatools;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.TypeReference;

import java.lang.reflect.Array;
import java.util.HashMap;
import java.util.Map;

/**
 * 数据装换工具
 *
 * @author List
 */
public class DataConversionUtils {

    /**
     * json字符串转换为对象
     * @param jsonStr json格式字符串
     * @param targetClass 转换后对象类型
     * @return 装换后对象数据
     */
    public static Object objectJsonToObject(String jsonStr,Class targetClass) {
        HashMap<String,Object> map = JSON.parseObject(jsonStr, new TypeReference<HashMap<String, Object>>() {
        });
         for (Map.Entry<String, Object> entry : map.entrySet()) {
             Object value = entry.getValue();
             if (value instanceof JSONArray ) {
                 Class itemClass = null;
                 JSONArray item =  (JSONArray) value;
                 if (item.isEmpty()){
                     continue;
                 }
                 itemClass = ((JSONArray) value).get(0).getClass();
                 Object[] newValue = (Object[])Array.newInstance(itemClass, item.size());
                 for (int i = 0; i < item.size(); i++) {
                     newValue[i] = item.get(i);
                 }
                 entry.setValue(newValue);
             }
         }
        return JSONObject.parseObject(JSONObject.toJSONString(map), targetClass);
    }


}
